import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { orderApi, type Order, type CreateOrderRequest } from '@/api/order'
import { ElMessage } from 'element-plus'

export interface OrderItem {
  productId: number
  skuId?: number
  productName: string
  productImage?: string
  skuSpecifications?: any
  price: number
  quantity: number
  totalAmount: number
}

export interface OrderInfo {
  items: OrderItem[]
  consigneeName: string
  consigneePhone: string
  consigneeAddress: string
  shippingFee: number
  pointsAmount: number
  buyerMessage?: string
  totalAmount: number
  goodsAmount: number
}

export const useOrderStore = defineStore('order', () => {
  // 状态
  const orders = ref<Order[]>([])
  const currentOrder = ref<Order | null>(null)
  const orderInfo = ref<OrderInfo | null>(null)
  const loading = ref(false)

  // 计算属性
  const orderCount = computed(() => orders.value.length)

  // 设置订单信息（用于立即购买）
  const setOrderInfo = (info: OrderInfo) => {
    orderInfo.value = info
  }

  // 清除订单信息
  const clearOrderInfo = () => {
    orderInfo.value = null
  }

  // 创建订单
  const createOrder = async (orderData: CreateOrderRequest): Promise<{ orderId: number; orderNo: string } | null> => {
    loading.value = true
    try {
      const response = await orderApi.createOrder(orderData)
      if (response.code === 200) {
        ElMessage.success('订单创建成功')
        return response.data
      } else {
        ElMessage.error(response.message || '创建订单失败')
        return null
      }
    } catch (error) {
      console.error('创建订单失败:', error)
      ElMessage.error('创建订单失败')
      return null
    } finally {
      loading.value = false
    }
  }

  // 分页信息
  const totalPages = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)

  // 获取订单列表
  const getOrders = async (params?: any) => {
    loading.value = true
    try {
      const response = await orderApi.getOrders(params)
      if (response.code === 200) {
        orders.value = response.data?.list || []
        totalPages.value = response.data?.totalPages || 0
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      ElMessage.error('获取订单列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取订单详情
  const fetchOrderById = async (id: number) => {
    loading.value = true
    try {
      const response = await orderApi.getOrderById(id)
      if (response.code === 200) {
        currentOrder.value = response.data
        return response.data
      } else {
        ElMessage.error('订单不存在')
        return null
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      ElMessage.error('获取订单详情失败')
      return null
    } finally {
      loading.value = false
    }
  }

  // getOrderById 方法（fetchOrderById的别名，保持API一致性）
  const getOrderById = fetchOrderById

  // 支付订单
  const payOrder = async (orderId: number, paymentMethod: string) => {
    loading.value = true
    try {
      const response = await orderApi.payOrder(orderId, paymentMethod)
      if (response.code === 200) {
        ElMessage.success('支付成功')
        // 更新订单状态
        await fetchOrderById(orderId)
        return true
      } else {
        ElMessage.error(response.message || '支付失败')
        return false
      }
    } catch (error) {
      console.error('支付失败:', error)
      ElMessage.error('支付失败')
      return false
    } finally {
      loading.value = false
    }
  }

  // 取消订单
  const cancelOrder = async (id: number) => {
    loading.value = true
    try {
      const response = await orderApi.cancelOrder(id)
      if (response.code === 200) {
        ElMessage.success('订单已取消')
        // 刷新订单列表
        await getOrders()
        return true
      } else {
        ElMessage.error(response.message || '取消订单失败')
        return false
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
      return false
    } finally {
      loading.value = false
    }
  }

  // 确认收货
  const confirmOrder = async (id: number) => {
    loading.value = true
    try {
      const response = await orderApi.confirmOrder(id)
      if (response.code === 200) {
        ElMessage.success('确认收货成功')
        // 刷新订单列表
        await getOrders()
        return true
      } else {
        ElMessage.error(response.message || '确认收货失败')
        return false
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    orders,
    currentOrder,
    orderInfo,
    loading,
    totalPages,
    currentPage,
    pageSize,
    
    // 计算属性
    orderCount,
    
    // 方法
    setOrderInfo,
    clearOrderInfo,
    createOrder,
    getOrders,
    fetchOrderById,
    getOrderById,
    payOrder,
    cancelOrder,
    confirmOrder,
  }
})